package com.simulate2.demo.util;

import com.simulate2.demo.dao.CommisionRepository;
import com.simulate2.demo.entity.Commision;
import com.simulate2.demo.entity.Date_commision;
import com.simulate2.demo.entity.User;
import com.simulate2.demo.service.MongoDbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 用于多线程
 */
@Service
public class MongoUtil {
    @Autowired
    private CommisionRepository commisionRepository;
    @Autowired
    private MongoDbService mongoDbService;

    /**
     * 遍历user表中的每一个用户，计算其当日分佣
     *
     * @param date
     */
    @Async("taskExecutor")
    public CompletableFuture<String> caluCommision(Integer date, BigDecimal commisionPerCredit, List<User> userList) {

        List<Commision> commisions = new ArrayList<>(10000);
        for (User user : userList) {
            BigDecimal activeCredit = new BigDecimal(user.getActiveCredit());
            BigDecimal userCommision = commisionPerCredit.multiply(activeCredit).setScale(2,BigDecimal.ROUND_HALF_DOWN) ;

            //先判断数据库中是否存在该用户的记录？若有，则取回，添加一条记录后更新，否则建立该用户的记录
            mongoDbService.myUpsert(user.getId(),date,userCommision);
        }

        return CompletableFuture.completedFuture("我是一个线程");
    }

}
